import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'th_credentials.dart';
import 'th_credentials_manager_platform_interface.dart';
import 'th_result.dart';

/// An implementation of [ThCredentialsManagerPlatform] that uses method channels.
class MethodChannelThCredentialsManager extends ThCredentialsManagerPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('th_credentials_manager');

  @override
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>(
      'getPlatformVersion',
    );
    return version;
  }

  @override
  Future<THResult<List<THCredentials>>> getAllCredentials() async {
    final res = await methodChannel.invokeMethod<Map>(
      'getAllCredentials',
    );
    THResult<List<THCredentials>> result = THResult.fromJson(res);
    List<THCredentials> all = [];
    if (result.rawData is Map) {
      result.rawData?.forEach((e) {
        all.add(THCredentials.fromJson(e));
      });
    }
    result.data = all;
    return result;
  }

  @override
  Future<THResult<bool>> deleteCredentialsBy(String borderAgentID) async {
    final res = await methodChannel.invokeMethod<Map>(
      'deleteCredentialsBy',
      borderAgentID,
    );
    THResult<bool> result = THResult.fromJson(res);
    result.data = result.rawData ?? false;

    return result;
  }

  @override
  Future<THResult<bool>> storeCredentials({
    required String borderAgentID,
    required String activeDataSet,
  }) async {
    final res = await methodChannel.invokeMethod<Map>(
      'storeCredentials',
      {
        "borderAgentID": borderAgentID,
        "activeDataSet": activeDataSet,
      },
    );
    THResult<bool> result = THResult.fromJson(res);
    result.data = result.rawData ?? false;
    return result;
  }

  @override
  Future<THResult<bool>> isPreferred({
    required String activeDataSet,
  }) async {
    final res = await methodChannel.invokeMethod<Map>(
      'isPreferred',
      activeDataSet,
    );

    THResult<bool> result = THResult.fromJson(res);
    result.data = result.rawData ?? false;
    return result;
  }
}
